using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ByHand.Model;
using ByHand.Data;
using ByHand.Services.Interfaces;
using ByHand.Data.Interfaces;
using ByHand.Services.Code;

namespace ByHand.Services.Implements
{
    public class OrderDetailService : RepositoryBase<OrderDetail>, IOrderDetailService
    {
        public OrderDetailService(IDatabaseFactory DbFactory) : base(DbFactory) { }

        public void MaintainDetails(List<OrderDetail> details, int p1)
        {
            var exists = (from o in this.All()
                          where o.OrderID == p1
                          select o).ToList();
            var lstToAdd = new List<OrderDetail>();
            foreach (var item in details)
            {
                var match = (from o in exists
                             where o.OptionsValue.Equals(item.OptionsValue)
                             select o).FirstOrDefault();
                if (match != null)
                {
                    exists.Remove(match);
                    match.Quantity = item.Quantity;
                    this.Update(match);
                }
                else
                {
                    lstToAdd.Add(item);
                }
            }
            foreach (var item in exists)
            {
                this.Delete(item);
            }
            foreach (var item in lstToAdd)
            {
                this.Add(item);
            }
        }

        public List<OrderDetail> GetByOrder(int oID)
        {
            return (from od in ByHandDB.OrderDetails
                    where od.OrderID == oID
                    select od).ToList();
        }
    }
}
